<template>
    <div>
        <el-form-item>
            <el-button 
                style="margin: auto" 
                type="primary" 
                @click="getSectionInfo"
                :disabled="selectedCourses.length === 0"
                :loading="loadingSections"
            >
                获取小节信息
            </el-button>
        </el-form-item>
        <el-form-item>
            <el-table 
                :data="filteredSections" 
                border 
                height="245" 
                style="width: 100%" 
                @selection-change="handleSectionSelect"
            >
                <el-table-column type="selection" width="55" />
                <el-table-column prop="name" label="章节名称" width="300" />
                <el-table-column prop="subName" label="类型" width="200" />
                <el-table-column label="学习时长" width="120">
                    <template #default="{ row }">
                        <span v-if="row.videoLength > 0">
                            {{ formatDuration(row.videoLength) }}
                        </span>
                        <span v-else class="no-duration">
                            无需学习
                        </span>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="100">
                    <template #default="{ row }">
                        <el-button 
                            link 
                            type="primary" 
                            @click="previewSection(row)"
                        >
                            详情
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-form-item>
        <el-form-item>
            <el-button 
                style="margin: auto" 
                type="success" 
                @click="startParallelTasks"
                :disabled="selectedSections.length === 0"
                :loading="processing"
            >
                开始刷课（共 {{ totalDuration }} 分钟）
            </el-button>
        </el-form-item>
    </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import axios from "axios";
import { ElMessage, ElNotification } from "element-plus";

// 课程小节信息接口定义
interface Section {
    cellId: string;      // 小节唯一标识
    name: string;        // 小节名称
    subName: string;     // 小节类型
    videoLength: number; // 视频时长（秒）
    completed?: boolean; // 是否已完成
}

// 组件属性定义
const props = defineProps({
    token: {
        type: String,
        required: true    // 用户访问令牌
    },
    selectedCourses: {
        type: Array,
        required: true    // 选中的课程列表
    }
})

const emit = defineEmits(['update-tasks'])

// 状态管理
const sections = ref<Section[]>([])           // 所有小节列表
const selectedSections = ref<Section[]>([])   // 选中的小节列表
const processing = ref(false)                 // 刷课处理状态
const loadingSections = ref(false)           // 小节加载状态

// 计算属性：过滤出未完成且有视频的小节
const filteredSections = computed(() => {
    return sections.value.filter(section => 
        !section.completed &&
        section.videoLength > 0
    )
})

// 计算属性：计算选中小节的总时长（分钟）
const totalDuration = computed(() => {
    return Math.ceil(selectedSections.value.reduce((sum, s) => sum + s.videoLength, 0) / 60)
})

// 格式化时长为 MM:SS 格式
const formatDuration = (seconds: number) => {
    const mins = Math.floor(seconds / 60)
    const secs = seconds % 60
    return `${mins}:${secs.toString().padStart(2, '0')}`
}

// 获取课程小节信息
const getSectionInfo = async () => {
    loadingSections.value = true
    sections.value = []
    
    try {
        // 使用Set去重，避免重复小节
        const existingIds = new Set<string>()
        
        // 并行获取所有选中课程的小节信息
        await Promise.all(props.selectedCourses.map(async (course: any) => {
            const courseId = course.menus[0]?.courseOpenId
            if (!courseId) return

            // 获取课程目录结构
            const response = await axios.get('/jxjyzx/studyLearn/courseDirectoryProcess', {
                params: { courseOpenId: courseId },
                headers: { 'access-token': props.token }
            })

            // 遍历课程结构：模块->主题->小节
            response.data.data.moduleList.forEach((module: any) => {
                module.topics.forEach((topic: any) => {
                    topic.cells.forEach((cell: any) => {
                        // 只添加有视频且未添加过的小节
                        if (cell.videoLength > 0 && !existingIds.has(cell.id)) {
                            sections.value.push({
                                cellId: cell.id,
                                name: cell.name,
                                subName: cell.subName,
                                videoLength: Number(cell.videoLength) || 0,
                                completed: cell.isComplete
                            })
                            existingIds.add(cell.id)
                        }
                    })
                })
            })
        }))

        ElNotification.success(`获取到 ${sections.value.length} 个小节`)
    } catch (error) {
        ElMessage.error('获取小节信息失败')
    } finally {
        loadingSections.value = false
    }
}

// 开始并行处理选中的小节
const startParallelTasks = async () => {
    // 筛选有效的小节（有视频时长）
    const validSections = selectedSections.value.filter(s => s.videoLength > 0)
    if (validSections.length === 0) return

    processing.value = true

    // 创建任务进度追踪对象
    const activeTasks = validSections.map(section => ({
        id: section.cellId,
        name: section.name.substring(0, 20) + (section.name.length > 20 ? '...' : ''),
        total: section.videoLength,
        remaining: section.videoLength,
        percentage: 0
    }))

    emit('update-tasks', activeTasks)

    try {
        // 并行处理所有选中的小节
        await Promise.all(validSections.map(async (section) => {
            // 1. 获取小节详情
            const detailRes = await axios.get('/jxjyzx/studyLearn/cellDetail', {
                params: { cellId: section.cellId },
                headers: { 'access-token': props.token }
            })

            // 2. 模拟视频播放进度
            await new Promise<void>((resolve) => {
                const startTime = Date.now()
                const task = activeTasks.find(t => t.id === section.cellId)
                if (!task) return resolve()

                // 每秒更新进度
                const timer = setInterval(() => {
                    const elapsed = Math.floor((Date.now() - startTime) / 1000)
                    if(task) {
                        task.remaining = Math.max(section.videoLength - elapsed, 0)
                        task.percentage = Math.min((elapsed / section.videoLength) * 100, 100)
                    }

                    emit('update-tasks', [...activeTasks])

                    if (elapsed >= section.videoLength) {
                        clearInterval(timer)
                        resolve()
                    }
                }, 1000)
            })

            // 3. 提交学习记录
            await axios.post('/jxjyzx/studyLearn/leaveCellLog', {
                id: detailRes.data.data.cellLogId,
                stopSeconds: 0,
                videoEndTime: section.videoLength
            }, {
                headers: { 'access-token': props.token }
            })

            section.completed = true
        }))

        ElNotification.success('所有任务已完成！')
    } catch (error) {
        ElMessage.error('部分任务执行失败')
    } finally {
        processing.value = false
        emit('update-tasks', [])
    }
}

// 处理小节选择变化
const handleSectionSelect = (sections: Section[]) => {
    selectedSections.value = sections.filter(s => s.videoLength > 0)
}

// 预览小节详情
const previewSection = (section: Section) => {
    ElMessage.info({
        message: `章节详情：${section.name}`,
        duration: 2000
    })
}
</script>

<style scoped>
/* 无学习时长的小节样式 */
.no-duration {
    color: #999;
    font-style: italic;
}
</style>